﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Media.Imaging;
using System.Threading;
using System.Collections.ObjectModel;

namespace WpfImageDuplicates
{
    public class FileImageCollection : ObservableCollection<IFileImage>
    {
        public FileImageCollection()
        {
        }

        public void ClearAllItems()
        {
            ClearItems();
        }

        public FileImageCollection(string pathName)
        {
            AddByPath(pathName);
        }

        public FileImageCollection(params string[] pathNames)
        {
            AddByPathNames(pathNames);
        }

        public List<IFileImage> AddByPath(string pathName)
        {
            List<IFileImage> results = new List<IFileImage>();
            var images = GetImagesFromPath(pathName);

            foreach (var image in images)
            {
                Add(image);
                results.Add(image);
            }

            return results;
        }

        public List<IFileImage> AddByPathNames(params string[] pathNames)
        {
            List<IFileImage> results = new List<IFileImage>();

            foreach (var pathName in pathNames)
            {
                results.AddRange(AddByPath(pathName));
            }

            return results;
        }

        public bool Delete(IFileImage fileImage)
        {
            if (this.Remove(fileImage))
            {
                fileImage.Delete();
                return true;
            }

            return false;
        }

        public static List<FileImage> GetImagesFromPath(string path)
        {
            List<FileImage> result = new List<FileImage>();

            var files = Directory.GetFiles(path);
            Thread.Sleep(10);

            foreach (var file in files)
            {
                string ext = System.IO.Path.GetExtension(file);
                if (ext.Contains("jpg") || ext.Contains("gif"))
                {
                    FileImage v = new FileImage(file);
                    v.ThumbnailSet += new EventHandler(v_ThumbnailSet);
                    result.Add(v);
                }
            }

            return result;
        }

        public static void v_ThumbnailSet(object sender, EventArgs e)
        {
            FileImage fi = sender as FileImage;
            if (fi.ThumbnailCached != null)
            {
                if (Settings.Values.WantFilterThumbnails)
                {
                    var bm = fi.ThumbnailCached;
                    fi.ThumbnailCached = Window1._filters.ApplyFilters(bm);
                }
            }
        }
    }
}
